import HoverPlateNumber from '@/components/HoverPlateNumber';
import type { ProDescriptionsItemProps } from '@ant-design/pro-components';
import { ProDescriptions, ModalForm } from '@ant-design/pro-components';
import { message, Timeline } from 'antd';
import { useEffect, useState } from 'react';
import ImageModal from './components/ImageModal';
import { getParkingRecord } from './service';
import styles from './style.less';
import type { ParkingRecordTableListItem, PatrolRecordItem } from './types.d';
import { ParkingRecordStatus } from './types.d';
import { handleInOutType, handleTime } from '@/utils/utils';
const PLATE_COLOR_MAP = new Map()
  .set(0, '-')
  .set(1, '蓝')
  .set(2, '黄')
  .set(3, '白')
  .set(4, '黑')
  .set(5, '绿');
const ifTimeSame = (t1: string | Date, t2: string | Date) => {
  const diff = new Date(t1).getTime() - new Date(t2).getTime();
  return diff === 0;
};

const ColoredText = (props: {
  text: string;
  color?: string;
  weight?: string | number;
  style?: React.CSSProperties;
}) => {
  const { text, color = '#000', weight = 'bold', style } = props;
  return (
    <span
      style={{
        fontWeight: weight === 'bold' ? weight : Number(weight || 500),
        color,
        ...style,
      }}
    >
      {text}
    </span>
  );
};
export default (props: { recordId: string; visible: boolean; close: () => void }) => {
  const { recordId, visible, close } = props;
  const [currRecord, setCurrRecord] = useState<ParkingRecordTableListItem>();

  useEffect(() => {
    if (recordId && recordId.length > 0) {
      getParkingRecord(recordId).then((res) => {
        if (res?.success) {
          setCurrRecord(res.data);
          return;
        } else {
          message.error({ key: 'subFlow', content: res?.message });
          return;
        }
      });
    }
  }, [recordId]);
  const RecordStatus =
    currRecord?.status == ParkingRecordStatus.NORMAL
      ? { text: ' 正常 ', color: '#666', des: false }
      : { text: ' 异常 ', color: 'red', des: true };
  const ifEnd = currRecord?.isEnded;

  const getPatrolColumns = (patrolType: string): ProDescriptionsItemProps<PatrolRecordItem>[] => {
    return [
      {
        title: patrolType == 'patrol' ? '巡检设备' : '收费员',
        dataIndex: 'patrolIdentiyCode',
        renderText: (_, record) =>
          patrolType == 'patrol'
            ? record.patrolIdentiyCode
            : `${record.patrolIdentiyName}(${record.patrolIdentiyCode})`,
      },
      {
        title: '车牌颜色',
        dataIndex: 'plateNumberColor',
        renderText: (text) => PLATE_COLOR_MAP.get(text),
      },

      {
        title: '车牌图片',
        dataIndex: 'plateImageUrl',
        render: (_, record) => (
          <HoverPlateNumber plateImageUrl={record.plateImageUrl} plateNumber={record.plateNumber} />
        ),
      },
      {
        title: '车牌号码',
        dataIndex: 'plateNumber',
        renderText: (text) => text || '暂无数据',
      },
      {
        title: '巡检图片',
        dataIndex: 'composeImageUrl',
        render: (_, record) =>
          record.composeImageUrl ? <ImageModal eventUrl={record.composeImageUrl} /> : '暂无图片',
      },
      {
        title: '巡检时间',
        valueType: 'dateTime',
        dataIndex: 'patrolTime',
      },
    ];
  };
  return (
    <ModalForm
      width="75vw"
      submitter={false}
      className={styles.detail}
      visible={visible}
      title={`${currRecord?.parkingLotName} - ${currRecord?.spotId}`}
      modalProps={{ destroyOnClose: true, onCancel: close }}
    >
      <div className={styles.subTime}>
        <Timeline mode="left" pending={!ifEnd && '停车中'}>
          {currRecord?.inType == 'sensor' && (
            <Timeline.Item label={handleTime(currRecord?.createTime)} color="green">
              <h4>车辆驶入，记录创建</h4>
              <div>
                当前驶入状态由
                <ColoredText text={handleInOutType(currRecord?.inType)} />
                上报
              </div>
              <div>车辆驶入时间：{handleTime(currRecord?.inTime)}</div>
              <div>
                当前记录状态
                <ColoredText text={RecordStatus.text} color={RecordStatus.color} />
              </div>
              {/* {RecordStatus.des &&
              currRecord?.description.map((item) => (
                <div>
                  <ColoredText text={item || ''} color="#555" weight={300} />
                </div>
              ))} */}
            </Timeline.Item>
          )}
          {currRecord?.patrolRecords.map((item, index) => {
            const currTime = item.patrolTime;
            return (
              <Timeline.Item
                key={new Date(item.createTime).getTime()}
                label={
                  currRecord.inType != 'sensor' || !ifTimeSame(currTime, currRecord.inTime)
                    ? handleTime(item.createTime)
                    : ''
                }
                color="green"
              >
                <>
                  <ProDescriptions<PatrolRecordItem>
                    title={
                      <span style={{ color: item.exception ? 'red' : 'black' }}>
                        第 {index + 1} 次巡检({item.patrolType == 'patrol' ? '巡检设备' : '收费员'})
                      </span>
                    }
                    dataSource={item}
                    columns={getPatrolColumns(item.patrolType)}
                  />
                  {currRecord.inType != 'sensor' && ifTimeSame(currTime, currRecord.inTime) && (
                    <>
                      <h4>车辆驶入，记录创建</h4>
                      <div>
                        当前驶入状态由
                        <ColoredText text={handleInOutType(currRecord?.inType)} />
                        上报
                      </div>
                      <div>车辆驶入时间：{handleTime(currRecord?.inTime)}</div>
                      <div>
                        当前记录状态
                        <ColoredText text={RecordStatus.text} color={RecordStatus.color} />
                      </div>
                    </>
                  )}

                  {item.description && (
                    <div>
                      异常描述：
                      <span
                        style={{
                          fontWeight: 500,
                        }}
                      >
                        {item.description}
                      </span>
                    </div>
                  )}
                </>
              </Timeline.Item>
            );
          })}
          {currRecord?.hasMorePatrol && (
            <Timeline.Item label=" " color="gray">
              <a
                onClick={async () => {
                  if (recordId && recordId.length > 0) {
                    const res = await getParkingRecord(recordId, true);
                    if (res?.success) {
                      setCurrRecord(res.data);
                      return;
                    } else {
                      message.error({ key: 'subFlow', content: res?.message });
                      return;
                    }
                  }
                }}
              >
                显示更多
              </a>
            </Timeline.Item>
          )}
          {ifEnd && (
            <Timeline.Item
              label={currRecord.outType == 'sensor' ? handleTime(currRecord.recordEndedTime) : ''}
              color={currRecord.outTime ? 'green' : 'red'}
            >
              <h4>车辆驶出</h4>
              <div>
                当前驶出状态由
                <ColoredText text={handleInOutType(currRecord?.outType)} />
                上报
              </div>
              <div>车辆驶出时间：{handleTime(currRecord.outTime)}</div>
            </Timeline.Item>
          )}
        </Timeline>
      </div>
    </ModalForm>
  );
};
